package cn.dlc.com.server;

import org.I0Itec.zkclient.ZkClient;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.dlc.com.config.Config;

public class ZookeeperServer {
	
	// 节点
	private String nodePath = "/config";
	
	// 基础配置类
	private Config config;
	
	// zookeeper客户端
	private ZkClient zkClient;
	
	public Config initConfig(Config config) {
		
		// 初始化对象
		if(config == null) {
			this.config = new Config(
					"jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8",
					"root", 
					"root", 
					"com.mysql.jdbc.Driver");	
		} else {
			this.config = config;
		}
		return this.config;
	}
	
	/**
	 * 更新配置
	 * 
	 * @param commonConfig
	 * @return
	 */
	public Config update(Config config) throws Exception {
		if(config != null) {
			this.config = config;
		}
		syncConfigToZookeeper();
		return this.config;
	}

	/**
	 * 将配置信息写入zookeeper节点存起来
	 * @throws Exception
	 */
	public void syncConfigToZookeeper() throws Exception {
		// 通过ZkClient去返回一个zkClient对象，
		// 等同于new ZooKeeper的方式去获取一个连接对象
		if(zkClient == null) {
			zkClient = new ZkClient("192.168.182.88:2181,192.168.182.89:2181,192.168.182.90:2181");
		}
		// 创建一个持久化的节点
		if(!zkClient.exists(nodePath)) {
			zkClient.createPersistent(nodePath);
		}
		ObjectMapper objectMapper = new ObjectMapper();
		// 将配置信息写入节点
		zkClient.writeData(nodePath, objectMapper.writeValueAsString(config));
	}
}
